<?php
namespace app\cmd\command;

use think\cache\driver\Redis;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Exception;
use think\Log;
use think\model\Merge;
use think\Upload;

class Download extends Command
{
    protected $output;
    private $lastcursor = 0;

    private $redis;

    private $stoptime;


    CONST CURSOR_PATH = "temp/cursor/cursor.txt";

    CONST DYSTEP = 36;
    CONST III_URL = "http://service.iiilab.com/video/download";
    CONST III_ID = "668d8cac7cef2566";
    CONST III_SEC = "9efbb4c2cefa268aead7e2b9977e7260";
//    CONST DOUYIN = "https://www.douyin.com/aweme/v1/hot_aweme/?app_id=%s&cursor=%s&count=36";
    CONST DOUYIN = "https://www.douyin.com/aweme/v1/hot_aweme/?app_id=1128&cursor=%s&count=36&parent_rid=%s&aweme_id=%s";

    protected function configure()
    {
        $this->setName('cj_download')->setDescription('下载抖音视频 ');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $this->output = $output;




        $output->writeln('over');
    }


    private function slt(){
        if($data = Db::name('video_dy')->field('aweme_id,down_url')){

        }
    }




    private function download($url, $id)
    {
// folder to save downloaded files to. must end with slash
        $destination_folder = 'temp/';

//        $url = $_POST['url'];
        $newfname = $destination_folder . $id . '.mp4';

        if(!$this->check_url($url)){
            $this->output->writeln('no:'.$newfname);
            return false;
        }
        $this->output->writeln($newfname);

        try{
            $file = fopen($url, "rb");
            if (isset($file) && $file) {
                $newf = fopen($newfname, "wb");
                if (isset($newf) && $newf)
                    while (!feof($file)) {
                        fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
                    }
            }
            if ($file) {
                fclose($file);
            }
            if ($newf) {
                fclose($newf);
            }
        }catch (Exception $e) {
            return false;
        }


        return true;
    }

    function check_url($url)
    {
        $parseurl = parse_url($url);
        $host = $parseurl['host'];
        $path = $parseurl['path'];
        try{
            $fp = fsockopen($host, 80, $errno, $errstr, 10);
        }catch (Exception $e){
            return false;
        }
        if (!$fp) {
            return false;
        }
        fputs($fp, "GET {$path} HTTP/1.1 \r\nhost:{$host}\r\n\r\n");
        if (preg_match('/HTTP\/1.1 200/', fgets($fp, 1024))) {
            return true;
        } else {
            return false;
        }
    }
}

?>
